<template>
	<view>
		<zmm-watermark :watermark="userStore.watermark" v-if="userStore.watermark"></zmm-watermark>
		<!--导航栏-->
		<pageLayout
			:barTitle="title"
			:isSearchNull="isSearchNull"
			:isOpen="isOpen"
			@rightClick="clickSearch">
		</pageLayout>
		<!--查询弹窗-->
		<up-popup :z-index="90" :show="isOpen" @close="closeSearch" mode="top">
			<view @touchmove.stop.prevent>
			<scroll-view class="search" scroll-y="true" @touchmove.stop>
				<view class="search-form">
					<uni-forms ref="searchRef" :modelValue="searchModel" label-width="160rpx">
						<uni-forms-item label="仓库" v-if="checkPermi(['zhouyz:warehouse:list'])">
						  <uni-data-select
								v-model="searchModel.warehouseId"
						  	placeholder="请选择仓库"
						  	:localdata="warehouseList"></uni-data-select>
						</uni-forms-item>
						<uni-forms-item label="线索ID">
							<uni-easyinput v-model="searchModel.clueId" placeholder="请输入线索ID" />
						</uni-forms-item>
						<uni-forms-item label="跟进ID">
							<uni-easyinput v-model="searchModel.clueFollowId" placeholder="请输入跟进ID" />
						</uni-forms-item>
						<uni-forms-item label="商品名称">
							<uni-easyinput v-model="searchModel.productName" placeholder="请输入商品名称" />
						</uni-forms-item>
						<uni-forms-item label="客户姓名">
							<uni-easyinput v-model="searchModel.customerName" placeholder="请输入客户姓名" />
						</uni-forms-item>
						<uni-forms-item label="联系电话">
							<uni-easyinput v-model="searchModel.phone" placeholder="请输入联系电话" />
						</uni-forms-item>
						<uni-forms-item label="门店名称">
							<uni-easyinput v-model="searchModel.storeName" placeholder="请输入门店名称" />
						</uni-forms-item>
					</uni-forms>
					<view class="search-footer main-flex">
						<up-button
							class="search-footer-item"
							text="搜索"
							type="primary"
							@click="searchSubmit"
							icon="search"></up-button>
						<up-button
							class="search-footer-item"
							@click="resetSubmit"
							text="重置"></up-button>
					</view>
				</view>
			</scroll-view>
			</view>
		</up-popup>
		<view class="content">
			<!--操作-->
			<view class="operate main-flex" v-if="checkPermi(['zhouyz:salesmanClueFollowProduct:add'])">
				<view class="operate-item">
					<up-button
						class="operate-btn main-flex"
						size="mini"
						type="primary"
						@click="add()">
						<uni-icons class="operate-btn-icon" type="plusempty" size="28rpx" color="#ffffff"></uni-icons>
						<view class="operate-btn-text">添加</view>
					</up-button>
				</view>
			</view>
			<!--内容-->
			<view class="table">
				<ty-table
					:data="tableList"
					:columns="columns"
					:sortable="true"
					@row-click="rowClick"
					:cellClassName="() => 'table-cell'"
					:headerCellClassName="() => 'table-cell'"
					:rowClassName="() => 'table-row'"
					:isOperateBtn="(row) => {
						return checkPermi(['zhouyz:salesmanClueFollowProduct:edit']) && row.status === 0
						|| checkPermi(['zhouyz:salesmanClueFollowProduct:audit']) && row.status === 0
						|| checkPermi(['zhouyz:salesmanClueFollowProduct:deliver']) && row.status === 1
						|| checkPermi(['zhouyz:salesmanClueFollowProduct:remove'])
					}"
					stripe
					border>
					<template v-slot:left="{ row }">
						<view class="table-td-cell">
							<view class="table-td-row">
								线索ID：
								<text class="table-td-text">{{row.clueId}}</text></view>
							<view class="table-td-row" v-if="row.clueFollowId > 0">
								线索跟进ID：
								<text class="table-td-text">{{row.clueFollowId}}</text></view>
							<view class="table-td-row">
								客户：
								<text class="table-td-text"></text></view>
							<view class="table-td-row">
								联系电话：
								<text class="table-td-text"></text></view>
							<view class="table-td-row">
								门店名称：
								<text class="table-td-text"></text></view>
							<view class="table-td-row">
								商品名称：
								<text class="table-td-text">{{row.productName}}</text></view>
							<view class="table-td-row">
								批次号：
								<text class="table-td-text">{{row.batchNumber}}</text></view>
							<view class="table-td-row">
								试菜数量：
								<text class="table-td-text">{{row.testNumber}}</text></view>
							<view class="table-td-row" v-if="checkPermi(['zhouyz:purchaseOrder:price'])">
								采购单价：
								<text class="table-td-text">{{row.purchasePrice}}</text></view>
							<view class="table-td-row">
								销售单价：
								<text class="table-td-text">{{row.salesPrice}}</text></view>
							
						</view>
					</template>
					<template v-slot:right="{ row }">
						<view class="table-td-cell">
							<view class="table-td-row">
								申请人：
								<text class="table-td-text">{{row.applyName}}</text></view>
							<view class="table-td-row">
								申请时间：
								<text class="table-td-text">{{row.applyTime}}</text></view>
							<view class="table-td-row">
								仓库：
								<text class="table-td-text">{{row.warehouseName}}</text></view>
							<view class="table-td-row" v-if="row.warehousePickId">
								拣货人：
								<text class="table-td-text">{{row.warehousePickId}}</text></view>
							<view class="table-td-row" v-if="row.warehousePickId">
								拣货时间：
								<text class="table-td-text">{{row.warehousePickTime}}</text></view>
							<view class="table-td-row" v-if="row.auditName">
								审核人：
								<text class="table-td-text">{{row.auditName}}</text></view>
							<view class="table-td-row" v-if="row.auditName">
								审核时间：
								<text class="table-td-text">{{row.auditTime}}</text></view>
							<view class="table-td-row">
								状态：
								<uni-tag size="small" :class="`status${row.status}`" :text="arrText(salesmanClueFollowProductStatusList, row.status)" /></view>
							<view class="table-td-row">
								备注：
								<text class="table-td-text">{{row.remark}}</text></view>
						</view>
					</template>
					<template v-slot:operate="{ row }">
						<view class="table-td-operate table-cell table-td-row main-flex">
							<view v-if="checkPermi(['zhouyz:salesmanClueFollowProduct:edit']) && row.status === 0" class="table-operate-btn main-flex">
								<up-button
									size="mini"
									type="primary"
									@click.stop="add(row.id)">
									<uni-icons class="table-operate-btn-icon" type="compose" size="24rpx" color="#ffffff"></uni-icons>
									<view class="table-operate-btn-text">修改</view>
								</up-button>
							</view>
							<view v-if="checkPermi(['zhouyz:salesmanClueFollowProduct:audit']) && row.status === 0" class="table-operate-btn main-flex">
								<up-button
									size="mini"
									type="primary"
									@click.stop="edit(row, 1)">
									<uni-icons class="table-operate-btn-icon" type="auth" size="24rpx" color="#ffffff"></uni-icons>
									<view class="table-operate-btn-text">审核</view>
								</up-button>
							</view>
							<view v-if="checkPermi(['zhouyz:salesmanClueFollowProduct:deliver']) && row.status === 1" class="table-operate-btn main-flex">
								<up-button
									size="mini"
									type="primary"
									@click.stop="edit(row, 2)">
									<uni-icons class="table-operate-btn-icon" type="cloud-upload" size="24rpx" color="#ffffff"></uni-icons>
									<view class="table-operate-btn-text">发货</view>
								</up-button>
							</view>
							<view v-if="checkPermi(['zhouyz:salesmanClueFollowProduct:remove'])" class="table-operate-btn main-flex">
								<up-button
									class="table-operate-btn main-flex"
									size="mini"
									type="error"
									@click.stop="deleteFun(row.id)">
									<uni-icons class="table-operate-btn-icon" type="trash" size="20rpx" color="#ffffff"></uni-icons>
									<view class="table-operate-btn-text">删除</view>
								</up-button>
							</view>
						</view>
					</template>
					<template v-slot:empty>
						<view class="table-empty">
							<up-empty mode="data"/>
						</view>
					</template>
				</ty-table>
			</view>
			<!--分页-->
			<view class="pagination" v-show="total > 0">
				<ty-pagination
					:total="total"
					:pageSize="pageSize"
					:currentPage="pageNum"
					:pageSizes="[10, 20, 30, 50]"
					mode="simple"
					layout="first,prev,page,next,last"
					@sizeChange="sizeChange"
					@change="pageChange">
				</ty-pagination>
			</view>
		</view>
		
		<!--确认弹窗-->
		<up-popup :z-index="90" round="5" closeable :show="showEdit" @close="editCancel" mode="center">
			<view class="edit">
				<view class="edit-header">{{editTitle}}</view>
				<view class="edit-form">
					<uni-forms
						ref="editRef"
						:rules="editRules"
						:modelValue="editModel"
						label-width="160rpx">
						<uni-forms-item label="ID" name="id" style="display: none;">
							<view class="edit-form-checkbox main-flex">
								<uni-easyinput v-model="editModel.id" />
							</view>
						</uni-forms-item>
						<uni-forms-item label="审核状态" name="status" required v-if="editType === 1">
							<view class="edit-form-checkbox main-flex">
								<uni-data-checkbox v-model="editModel.status" :localdata="statusList" />
							</view>
						</uni-forms-item>
						<uni-forms-item label="取货仓库" v-if="editType === 2">
						  <uni-easyinput disabled v-model="editModel.warehouseName" placeholder="请输入试品数量" />
						</uni-forms-item>
						<uni-forms-item label="商品 "v-if="editType === 2">
						  <uni-easyinput disabled v-model="editModel.productName" placeholder="请输入试品数量" />
						</uni-forms-item>
						<uni-forms-item label="试品数量" name="testNumber" v-if="editType === 2">
						  <uni-easyinput type="number" v-model="editModel.testNumber" placeholder="请输入试品数量" />
						</uni-forms-item>
						<uni-forms-item label="备注" name="remark">
							<uni-easyinput type="textarea" v-model="editModel.remark" placeholder="请输入备注"></uni-easyinput>
						</uni-forms-item>
					</uni-forms>
					<view class="edit-footer main-flex">
						<up-button
							class="edit-footer-item"
							@click="editCancel"
							text="取消"></up-button>
						<up-button
							class="edit-footer-item"
							text="确认"
							type="primary"
							@click="editConfirm"></up-button>
					</view>
				</view>
			</view>
		</up-popup>
		
	</view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { computed, onMounted, ref, getCurrentInstance } from 'vue'
import { tab, auth, modal } from "@/plugins"
import { getTitle } from "@/utils/getter"
import { checkPermi, checkRole, checkOnlyPermi, checkOnlyRole } from "@/utils/permission"
import {
	salesmanClueFollowProduct,
	salesmanClueFollowProductDel,
	salesmanClueFollowProductAudit,
	salesmanClueFollowProductSend } from "@/api/erp_api/sale"
import { isObjectEmptySimple, copyText, arrText } from '@/utils/ty.js'
import useUserStore from '@/store/modules/user'
import { warehouse } from "@/api/erp_api/warehouse"
import { salesmanClueFollowProductStatusList } from '@/utils/config.js'

	const userStore = useUserStore()
	const { proxy } = getCurrentInstance()
	// 标题设置
	const title = ref('')
	const userId = ref('')
	onLoad(async (option) => {
		title.value = getTitle(userStore.menu)
		userId.value = option.userId ? option.userId : ''
		uni.setNavigationBarTitle({
			title: title.value 
		})
		if (checkPermi(['zhouyz:warehouse:list'])) {
			await getWarehouse()
		}
		uni.$on('refreshList', () => {
			getList()
		})
	})
	
	// 获取仓库
	const warehouseList = ref([])
	const getWarehouse = (res) => {
		return warehouse().then(res => {
			warehouseList.value = res.rows.map(item => {
				return {
					...item,
					value: item.id,
					text: item.name
				}
			}) || []
		})
	}
	
	// 搜索相关
	const isSearchNull = ref(true)
	const isOpen =  ref(false)
	const clickSearch = (val) => {
		isOpen.value = val
	}
	const closeSearch = (val) => {
		isOpen.value = false
	}
	// 确认搜索
	const searchRef = ref(null)
	const searchModel = ref({
		clueId: '',
		clueFollowId: '',
		productName: '',
		customerName: '',
		phone: '',
		storeName: '',
		warehouseId: ''
	})
	const searchSubmit = () => {
		pageNum.value = 1
		tableList.value = []
		isOpen.value = false
		searchFirst()
	}
	// 重置搜索
	const resetSubmit = () => {
		// searchRef.value.resetFields()
		searchModel.value = {
			clueId: '',
			clueFollowId: '',
			productName: '',
			customerName: '',
			phone: '',
			storeName: '',
			warehouseId: ''
		}
		if (userStore.warehouseId) {
			searchModel.value.warehouseId = userStore.warehouseId
		}
		isSearchNull.value = true
		isOpen.value = false
		searchFirst()
	}
	
	
	// 数据查询
	const pageNum = ref(1)
	const pageSize = ref(10)
	const total = ref(0)
	const tableList = ref([])
	const isLoading = ref(false)
	
	// 表格头部
	const columns = ref([
		{ title: '商品信息', key: 'left' },
		{ title: '试品信息', key: 'right', width: '330rpx' }
	])
	
	// 从第一页查询
	const searchFirst = () => {
		pageNum.value = 1
		tableList.value = []
		isSearchNull.value = isObjectEmptySimple(searchModel.value)
		getList()
	}
	//页数切换
	const pageChange = (page) => {
		pageNum.value = page
		getList()
	}
	//每页条数切换
	const sizeChange = (size) => {
		pageSize.value = size
		getList()
	}
	
	const getList = () => {
		const params = {
			pageNum: pageNum.value,
			pageSize: pageSize.value
		}
		if (searchModel.value.clueId) {
			params.clueId = searchModel.value.clueId
		}
		if (searchModel.value.clueFollowId) {
			params.clueFollowId = searchModel.value.clueFollowId
		}
		if (searchModel.value.productName) {
			params.productName = searchModel.value.productName
		}
		if (searchModel.value.customerName) {
			params.customerName = searchModel.value.customerName
		}
		if (searchModel.value.phone) {
			params.phone = searchModel.value.phone
		}
		if (searchModel.value.storeName) {
			params.storeName = searchModel.value.storeName
		}
		if (searchModel.value.warehouseId) {
			params.warehouseId = searchModel.value.warehouseId
		}
		// 团队点击进来
		if (userId.value) {
			params.applyId = userId.value
		}
		
		isLoading.value = true
		uni.showLoading({
			title: '数据加载中...'
		})
		salesmanClueFollowProduct(params).then(res => {
			tableList.value = res.rows || []
			total.value = res.total
			isLoading.value = false
			uni.hideLoading()
    }).catch(() => {
			isLoading.value = false
			uni.hideLoading()
		})
	}
	
	// 详情
	const rowClick = (row) => {
		uni.navigateTo({
			url: `/pages/sale/salesmanClueFollowProductDetail?id=${row.id}`
		})
	}
	
	// 编辑
	const add = (id) => {
		uni.navigateTo({
			url: id ? `/pages/sale/salesmanClueFollowProductAdd?id=${id}` : '/pages/sale/salesmanClueFollowProductAdd'
		})
	}
	
	const isSubmit = ref(false)
	
	//删除
	const deleteFun = (id) => {
		uni.showModal({
			title: '删除',
			content: `是否确认删除试品明细编号为"${id}"的数据项?`,
			success: function (res) {
				if (res.confirm) {
					deleteOne(id)
				}
			}
		})
	}
	const deleteOne = (id) => {
		if (isSubmit.value) return false
		isSubmit.value = true
		salesmanClueFollowProductDel({
			id
		}).then(res => {
			modal.showToast('删除成功')
			getList()
			isSubmit.value = false
		}).catch((err) => {
			modal.showToast(err)
			isSubmit.value = false
		})
	}
	
	
	// 编辑
	const showEdit = ref(false)
	const editType = ref('')
	const editTitle = ref('试品')
	
	//打开
	const edit = (row, type) => {
		showEdit.value = true
		editType.value = type
		editModel.value.id = row.id
		editModel.value.remark = row.remark
		if (type === 1) {
			editTitle.val = '试品审核'
		} else if (type === 2) {
			editTitle.val = '试品发货'
			editModel.value.testNumber = row.testNumber
			editModel.value.warehouseName = row.warehouseName
			editModel.value.productName = row.productName
		}
	}
	
	// 取消
	const editCancel = () => {
		showEdit.value = false
		editModel.value = {
			id: '',
			remark: '',
			status: '',
			testNumber: ''
		}
	}
	
	const editRef = ref(null)
	const editModel = ref({
		id: '',
		remark: '',
		status: '',
		testNumber: ''
	})
	const editRules = ref({
		status: {
			rules: [{ required: editType.value === 1, errorMessage: '请选择审核状态' }]
		}
	})
	const statusList = [{ value: 1, text: '审核通过'},{ value: 2, text: '审核不通过'}]
	const editConfirm = () => {
		editRef.value.validate().then(formRes => {
			if (isSubmit.value) return false
			isSubmit.value = true
			const params = {...formRes}
			if (editType.value === 1) {
				salesmanClueFollowProductAudit(params).then((res) => {
					modal.showToast(res.msg)
					editCancel()
					getList()
					isSubmit.value = false
				}).catch((err) => {
					modal.showToast(err)
					isSubmit.value = false
				})
			} else if (editType.value === 2) {
				params.status = 3
				salesmanClueFollowProductSend(params).then((res) => {
					modal.showToast(res.msg)
					editCancel()
					getList()
					isSubmit.value = false
				}).catch((err) => {
					modal.showToast(err)
					isSubmit.value = false
				})
			}
		})
	}
	
	// 分拣
	const pick = (id) => {
		uni.showModal({
			title: '试品分拣',
			content: `是否确认试品明细编号为"${id}"的商品分拣完成?`,
			success: function (res) {
				if (res.confirm) {
					pickOne(id)
				}
			}
		})
	}
	const pickOne = (id) => {
		if (isSubmit.value) return false
		isSubmit.value = true
		salesmanClueFollowProductAdd({
			id,
			status: 3,
			warehousePickId: userStore.user.userId
		}).then(res => {
			modal.showToast('分拣完成')
			getList()
			isSubmit.value = false
		}).catch((err) => {
			modal.showToast(err)
			isSubmit.value = false
		})
	}
	
	// 完成
	const complete = (id) => {
		uni.showModal({
			title: '试品完成',
			content: `是否确认试品明细编号为"${id}"的商品试品完成?`,
			success: function (res) {
				if (res.confirm) {
					completeOne(id)
				}
			}
		})
	}
	const completeOne = (id) => {
		if (isSubmit.value) return false
		isSubmit.value = true
		salesmanClueFollowProductAdd({
			id,
			status: 4
		}).then(res => {
			modal.showToast('试品完成')
			getList()
			isSubmit.value = false
		}).catch((err) => {
			modal.showToast(err)
			isSubmit.value = false
		})
	}
	onMounted(() => {
		if (userStore.warehouseId) {
			searchModel.value.warehouseId = userStore.warehouseId
		}
		searchFirst()
	})
</script>

<style scoped lang="scss">
	.status1 {
		background-color: #71d5a1;
		border-color: #71d5a1;
	}
	.status2 {
		background-color: #fa3534;
		border-color: #fa3534;
	}
	.status3 {
		background-color: #fcbd71;
		border-color: #fcbd71;
	}
	.status4 {
		background-color: #19be6b;
		border-color: #19be6b;
	}
</style>
